package com.places.googleplacesandmaps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(9)
public class OwnerLogin extends Activity implements View.OnClickListener {
		
	Intent i;
	Button btnLogin;
	EditText txtUsername, txtPassword;
	JSONArray jArray;
	JSONObject json_data;
	String loc_name="",loc_addr="",uname="",pwd="";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        setupVariables(); 
	}
	
	private void setupVariables() {
		btnLogin = (Button)findViewById(R.id.btnLogin);
        txtUsername = (EditText)findViewById(R.id.txtUsername);
        txtPassword = (EditText)findViewById(R.id.txtPassword);
    	
        btnLogin.setOnClickListener(this);
		InputStream is=null;
    	String line = null;
    	String result="";
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectNetwork() // or .detectAll() for all detectable problems
        .penaltyDialog()  //show a dialog
        .permitNetwork() //permit Network access 
        .build());
    	try{
        	
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new      
            HttpPost("http://project2.site11.com/getOwner.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.i("postData", response.getStatusLine().toString());
        }catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
        
        
        //parsing http response into string
        System.out.println("6");
        long h=1;
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            System.out.println("before converting");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection" +e.toString());
        }
        
        
        //parsing json
        try{	 
        	if(result!=null)
        	{	
        		jArray = new JSONArray(result);
            }
            }
        catch(JSONException e){
            Log.e("log_tag", "Error parsing data" +e.toString());
        }
	}
	
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.btnLogin:
            	            	
            	String username = txtUsername.getText().toString();
    			String password = txtPassword.getText().toString();
    			boolean success=false;
    			try
				{
					for(int i=0;i<jArray.length();i++)
					{
						json_data = jArray.getJSONObject(i);
						uname = json_data.getString("UserName");
						pwd = json_data.getString("Password");
						if(uname.equals(username) && pwd.equals(password))
						{
							loc_name = json_data.getString("ShopName");
							loc_addr = json_data.getString("Location");
							success=true;
							break;
						}
					}
				}
				catch(JSONException e){
		            Log.e("log_tag", "Error parsing data" +e.toString());
				}
				
			
				if (success){
					Context context = getApplicationContext();
					CharSequence text = "Login Successfull!";
					int duration = Toast.LENGTH_LONG;
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					Bundle basket = new Bundle();
        			basket.putString("username", username);
        			basket.putString("shopname", loc_name);
        			basket.putString("location", loc_addr);
        			i = new Intent(OwnerLogin.this, OwnerDetails.class);
        			i.putExtras(basket);
        			OwnerLogin.this.startActivity(i);
				}
				else{
					Dialog d= new Dialog(this);
					d.setTitle("Incorrect information");
					TextView tv= new TextView(this);
					tv.setText("Login information is incorrect");
					d.setContentView(tv);
					d.show();
					
				}
				
				break;
    		
        }
    }

	
}
